package org.chnxi.study.concurrent.future.completeablefuture;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CompletableFutureDemo1 {

    static ThreadPoolExecutor pool = new ThreadPoolExecutor(3 , 3 , 60,TimeUnit.SECONDS , new ArrayBlockingQueue(32));

    public static void main(String[] args) throws  Exception{

        CompletableFuture<String> completableFuture = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("aaaaaa" + Thread.currentThread().getName());
        }, pool).supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            return "Hello";
        }, pool)
                .thenApply(s -> {
                    System.out.println(Thread.currentThread().getName());
                    return s + " World";
                })
                .thenApply(String::toUpperCase)
                .thenCombine(CompletableFuture.completedFuture(" Java"), (s1, s2) -> {
                    System.out.println(Thread.currentThread().getName());
                    try {
                        TimeUnit.MILLISECONDS.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return s1 + s2;
                }).thenApply(s -> {return s;});
        System.out.println("这是主线程。。。"+Thread.currentThread().getName());

        String result = completableFuture.get();
        System.out.println("result = "+result);
        pool.shutdown();
    }

}
